package main

import (
	"context"
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
	"os"
	"os/signal"
	"strconv"
	"student-admin/app/middleware"
	"student-admin/app/routers"
	"syscall"
	"time"
)

func main() {
	r := gin.Default()
	r.Use(middleware.Cross())

	routers.InitRouter(r)

	hs := http.Server{
		Addr:         ":" + strconv.Itoa(8080),
		Handler:      r.Handler(),
		ReadTimeout:  15 * time.Second,
		WriteTimeout: 15 * time.Second,
	}

	go func() {
		if err := hs.ListenAndServe(); err != nil {
			fmt.Println("Server exiting with error: ", err)
		}
	}()

	// Graceful shutdown
	kill := make(chan os.Signal)
	signal.Notify(kill, syscall.SIGINT, syscall.SIGTERM, syscall.SIGHUP)
	sig := <-kill
	fmt.Printf("Received stop signal from system: %s\n", sig.String())

	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()

	_ = hs.Shutdown(ctx)
	time.Sleep(100 * time.Millisecond)
}
